import { login, getInfo } from '@/api/user';

// 登录状态、登录动作
const state = {
  // 秘钥
  token: localStorage.getItem("token"),
  // 其他用户信息
  roles: [] // 用户角色
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  }
};

const actions = {
  // 模拟用户登录
  login({ commit }, userInfo) {
    return login(userInfo).then((res) => {
      commit("SET_TOKEN", res.data);
      localStorage.setItem("token", res.data);
    });
  },
  // 获取用户角色
  getInfo({ commit, state }) {
    return getInfo(state.token).then(({ data: roles }) => {
      commit("SET_ROLES", roles);
      return { roles }
    })
  },
  // 退出登录重置用户信息
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      localStorage.removeItem('token')
      resolve();
    })
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
